<?php

class Admin_ProductController extends JControllerAdmin
{
    /**
     * @return void
     */
    public function init()
    {
        $layout = Zend_Layout::getMvcInstance();
        $actionName = $this->_request->getActionName();
        switch ($actionName) {
            case 'add':
            case 'update':
                $layout->setLayout('admin/layout-admin-add');
                break;
        }
    }

    /**
     * @return void
     */
    public function indexAction()
    {
        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $messages = $flashMessenger->getMessages();
        $this->view->messages = $messages;

        $productTypePOJOs = Application_Model_ProductType::getProductTypes();
        $this->view->productTypePOJOs = $productTypePOJOs;

        // BEGIN: Tạo đối tượng Paginator
        $dbSelect = JDbAdapter::factory()
            ->select()
            ->from('PRODUCTS')
            ->where('Deleted = ?', false);

        // Tìm kiếm theo tên sản phẩm (nếu có)
        $keyWords = $this->_request->getParam('keyWords');
        if (isset($keyWords)) {
            $dbSelect->where("Name LIKE '%$keyWords%'");
            $this->view->enteredKeyWords = $keyWords;
        }

        // Lọc theo loại sản phẩm (nếu có)
        $productTypeID = $this->_request->getParam('productTypeID');
        if (isset($productTypeID)) {
            $dbSelect->where('ProductTypeID = ?', $productTypeID);
            $this->view->selectedProductTypeID = $productTypeID;
        }

        $paginator = new Zend_Paginator(
            new Zend_Paginator_Adapter_DbSelect($dbSelect)
        );
        // END: Tạo đối tượng Paginator

        // Get and set current page
        $page = $this->_request->getParam('page');
        $paginator->setCurrentPageNumber($page);
        $products = $paginator->getItemsByPage($page);

        // Assign data for view
        $this->view->products = $products;
        $this->view->paginator = $paginator;
    }

    /**
     * @return void
     */
    public function addAction()
    {
        $this->view->messages = array();

        $productTypePOJOs = Application_Model_ProductType::getProductTypes();
        $this->view->productTypePOJOs = $productTypePOJOs;

        $isPost = $this->_request->getParam('isPost');
        if (isset($isPost)) {
            $name = $this->_request->getParam('name');
            $description = $this->_request->getParam('description');
            $expired = new Zend_Date($this->_request->getParam('expired'));
            $orginalAmount = $this->_request->getParam('orginalAmount');
            $oldPrice = $this->_request->getParam('oldPrice');
            $newPrice = $this->_request->getParam('newPrice');
            $lat = $this->_request->getParam('lat');
            $lng = $this->_request->getParam('lng');
            $productTypeID = $this->_request->getParam('productTypeID');

            $newProductID = Application_Model_Product::addProduct(
                $name, $description, $expired, $orginalAmount,
                $oldPrice, $newPrice, $lat, $lng, $productTypeID
            );
            if ($newProductID == 0) {
                $this->view->messages = array('Add Product Fail!!!');
                $this->view->name = $name;
                $this->view->description = $description;
                $this->view->expired = $expired->get('d - M - y');
                $this->view->orginalAmount = $orginalAmount;
                $this->view->oldPrice = $oldPrice;
                $this->view->newPrice = $newPrice;
                $this->view->lat = $lat;
                $this->view->lng = $lng;
                $this->view->selectedProductTypeID = $productTypeID;
            } else {
                /** @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
                $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                $task = $this->_request->getParam('task');
                switch ($task) {
                    case 'apply':
                        $flashMessenger->addMessage('Add Product Successfully!!!');
                        $this->redirect("/admin/product/update/productID/$newProductID");
                        break;
                    case 'apply-and-close':
                        $flashMessenger->addMessage('Add Product Successfully!!!');
                        $this->redirect('/admin/product/index');
                        break;
                    case 'apply-and-new':
                        $this->view->messages = array('Add Product Successfully!!!');
                        break;
                    default:
                        $flashMessenger->addMessage('Cannot Determine Next Task');
                        $this->redirect('/admin/product/index');
                        break;
                }
            }
        }
    }

    /**
     * @return void
     */
    public function deleteAction()
    {
        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');

        $isPost = $this->_request->getParam('isPost');
        if (!isset($isPost)) {
            $flashMessenger->addMessage('Cannot Execute This URL Directly');
            $this->redirect('/admin/product/index');
        }

        $productIDs = $this->_request->getParam('productIDs');
        if (!Application_Model_Product::deleteProducts($productIDs)) {
            $flashMessenger->addMessage('Delete Fail');
        } else {
            $var = '';

            $length = count($productIDs);
            for ($i = 0; $i < $length - 1; $i++) {
                $var .= $productIDs[$i] . ', ';
            }
            $var .= $productIDs[$length - 1];

            $flashMessenger->addMessage("Delete $var Successfully");
        }

        $this->redirect($_SERVER['HTTP_REFERER']);
    }

    /**
     * @return void
     */
    public function updateAction()
    {
        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $messages = $flashMessenger->getMessages();
        $this->view->messages = $messages;

        $isPost = $this->_request->getParam('isPost');
        if (isset($isPost)) {
            $id = $this->_request->getParam('productID');
            $name = $this->_request->getParam('name');
            $description = $this->_request->getParam('description');
            $expired = new Zend_Date($this->_request->getParam('expired'));
            $orginalAmount = $this->_request->getParam('orginalAmount');
            $oldPrice = $this->_request->getParam('oldPrice');
            $newPrice = $this->_request->getParam('newPrice');
            $lat = $this->_request->getParam('lat');
            $lng = $this->_request->getParam('lng');
            $productTypeID = $this->_request->getParam('productTypeID');

            $success = Application_Model_Product::updateProduct(
                $id, $name, $description, $expired, $orginalAmount,
                $oldPrice, $newPrice, $lat, $lng, $productTypeID
            );
            if (!$success) {
                $this->view->messages = array('Update Product Fail');
                $this->view->name = $name;
                $this->view->description = $description;
                $this->view->expired = $expired->get('d - M - y');
                $this->view->orginalAmount = $orginalAmount;
                $this->view->oldPrice = $oldPrice;
                $this->view->newPrice = $newPrice;
                $this->view->lat = $lat;
                $this->view->lng = $lng;
                $this->view->selectedProductTypeID = $productTypeID;
            } else {
                $task = $this->_request->getParam('task');
                switch ($task) {
                    case 'apply':
                        $this->view->messages = array('Update Product Successfully');
                        $this->view->name = $name;
                        $this->view->description = $description;
                        $this->view->expired = $expired->get('d - M - y');
                        $this->view->orginalAmount = $orginalAmount;
                        $this->view->oldPrice = $oldPrice;
                        $this->view->newPrice = $newPrice;
                        $this->view->lat = $lat;
                        $this->view->lng = $lng;
                        $this->view->selectedProductTypeID = $productTypeID;
                        break;
                    case 'apply-and-close':
                        $flashMessenger->addMessage('Update Product Successfully');
                        $this->redirect('/admin/product/index');
                        break;
                    default:
                        $flashMessenger->addMessage('Cannot Determine Next Task');
                        $this->redirect('/admin/product/index');
                        break;
                }
            }
        } else {
            $productID = $this->_request->getParam('productID');
            $productPOJO = Application_Model_Product::getProduct($productID);
            if ($productPOJO == null) {
                $flashMessenger->addMessage('This ID does not exist');
                $this->redirect('/admin/product/index');
            }
            $this->view->productPOJO = $productPOJO;
        }

        $productTypePOJOs = Application_Model_ProductType::getProductTypes();
        $this->view->productTypePOJOs = $productTypePOJOs;

        $this->render('add');
    }
}
